import React, { useEffect, useRef } from 'react';
import { connect, withRouter } from 'umi';
import { INIT_WEBSCENE } from '../../constants/action-types';

import { useEffectOnce } from 'react-use';
import styles from '../page_common.less';
import cls from 'classnames';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { DrawProvider, useDrawStore } from './multiDraw/store';

import DrawTree from './multiDraw/drawTree';
import DrawPath from './multiDraw/drawPath';
import { getCurTask } from './multiDraw/drawFn';

const IndexPage = props => {
  const viewDiv = useRef(null);
  const [drawState, drawDispatch] = useDrawStore();
  const drawStateRef = useRef(drawState);

  useEffect(() => {
    drawStateRef.current = drawState;
  });

  // 初始化地图
  useEffectOnce(() => {
    props.dispatch({
      type: INIT_WEBSCENE,
      payload: {
        container: viewDiv.current,
        basemapID: 'streets-night-vector',
      },
    });

    init();
  });

  async function init() {
    const view = await viewUtils.isViewReady();
    view.on('click', event => {
      console.log(getCurTask(), 'trigger update');
      if (!getCurTask()) {
        view.hitTest(event).then(response => {
          response.results.some(result => {
            const graphic = result.graphic;
            console.log(graphic, drawStateRef.current);
            if (graphic && graphic.geometry) {
              if (drawStateRef.current[graphic.layer.id]) {
                drawStateRef.current[graphic.layer.id](graphic);
                return true;
              }
            }
            return false;
          });
        });
      }
    });
  }

  return (
    <div className={styles.wrapper}>
      <div className={cls(styles.viewContainer, 'view-container', 'main-page')}>
        <div ref={viewDiv} className={styles.viewDiv}></div>

        <DrawPath />
        <DrawTree />
      </div>
    </div>
  );
};

// export default IndexPage

const WrapIndexPage = props => {
  return (
    <DrawProvider>
      <IndexPage {...props} />
    </DrawProvider>
  );
};

export default connect(() => {
  return {};
})(WrapIndexPage);
